package com.stormragetech.arthas.codec;

import com.stormragetech.arthas.common.annotation.ResponseType;
import com.stormragetech.arthas.common.constant.Constant;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.log4j.Log4j2;

/**
 * description: http response encode implement
 *
 * @author: Xue Bin
 * @version: 1.0.0-SNAPSHOT
 */
@Log4j2
@Data
@AllArgsConstructor
public class ArthasHttpResponseEncodeHandler implements ArthasHttpResponseEncode {

    private String data;
    private ResponseType type;

    @Override
    public FullHttpResponse process() {

        return ResponseHandler.handle(data, type);
    }

    private static class ResponseHandler {

        static FullHttpResponse handle(String data, ResponseType type) {
            if (null == data || null == type) {
                data = "server error !!!";
                type = ResponseType.ERROR;
            }
            ByteBuf buf = Unpooled.wrappedBuffer(data.getBytes());
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
            response.headers()
                    .add(Constant.CONTENT_TYPE, type.getValue())
                    .add(Constant.CONTENT_LENGTH, String.valueOf(buf.readableBytes()));
            return response;
        }
    }

    public static void main(String[] args) {
        ArthasHttpResponseEncodeHandler handler = new ArthasHttpResponseEncodeHandler("nihao", ResponseType.JSON);
        log.info(ResponseType.JSON.getValue());
        log.info(handler.process());
    }
}
